<template>
  <PlayGround v-if="$store.state.pk.status === 'playing'"></PlayGround>
  <MatchGround v-if="$store.state.pk.status === 'matching'"></MatchGround>
</template>

<script>
import PlayGround from '@/components/PlayGround.vue';
import MatchGround from '@/components/MatchGround.vue';
import {onMounted,onUnmounted} from 'vue';
import {useStore} from 'vuex';
export default {
  components: {
    PlayGround,
    MatchGround,
  },
  setup(){
    const store = useStore();
    const socketUrl=`ws://localhost:3000/websocket/${store.state.user.token}/`;
    let socket=null;//声明 socket 变量，用于存储 WebSocket 实例，初始值为 null（连接建立后会被赋值）
    onMounted(()=>{ 
      store.commit("updateOpponent",{
        username:"我的对手",
        photo:"https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png"
      });//测试数据

      socket=new WebSocket(socketUrl);//创建 WebSocket 实例，发起与服务端的连接
      socket.onopen=()=>{//连接成功建立,此后可以双向通信
        console.log("connected");
        store.commit("updateSocket",socket);//将 WebSocket 实例存储到 Vuex 的状态管理中
      }
      socket.onmessage=msg=>{ //收到服务端发送的消息
        const data=JSON.parse(msg.data);//msg.data 是服务端发送的原始数据，然后将原始数据解析为 JavaScript 对象 data
        if(data.event==="start-matching"){//收到后端传过来的event为start-matching则匹配成功
          store.commit("updateOpponent",{
            username:data.opponent_username,
            photo:data.opponent_photo,
          });
          setTimeout(()=>{//等待后端返回数据
            store.commit("updateStatus","playing");//两秒钟后跳转
          },2000);
          store.commit("updateGamemap",data.gamemap);//存储游戏地图实例
        }
      }
      socket.onclose=()=>{ 
        console.log("disconnected");
      }
    });
    onUnmounted(()=>{ 
      socket.close();//组件卸载时关闭 WebSocket 连接
      store.commit("updateStatus","matching");
    });
  }
}
</script>

<style scoped>
</style>